package org.adream.account.service.async;

import java.io.File;
import java.util.Date;

import javax.annotation.Resource;

import org.adream.account.dao.LogRestfulDao;
import org.adream.account.dao.RealNameTmpDao;
import org.adream.account.dao.UserDao;
import org.adream.account.dao.UserDetailDao;
import org.adream.account.dao.UserVerifyDao;
import org.adream.account.entity.RealNameTmpEntity;
import org.adream.account.entity.UserDetailEntity;
import org.adream.account.entity.UserEntity;
import org.adream.account.entity.UserVerifyEntity;
import org.adream.account.model.SynDream2020DataModel;
import org.adream.account.rest.api.model.FrontBasicInfoForm;
import org.adream.account.service.UserService;
import org.adream.account.service.cloudCollege.SynCloudCollegeService;
import org.adream.account.service.cloudCollege.SynCloudCollegeUserEntity;
import org.adream.account.service.library.SynLibraryService;
import org.adream.account.service.library.SynLibraryUserEntity;
import org.adream.account.service.scfire.SynScFireService;
import org.adream.account.service.scfire.SynScFireUserEntity;
import org.adream.account.util.Constant;
import org.adream.account.util.UUIDUtil;
import org.adream.account.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.sun.xml.bind.v2.runtime.reflect.opt.Const;

@Component
@EnableAsync
@Lazy
public class AsyncService {
	@Resource
	private TaskExecutor taskExecutor;
	
	@Autowired 
	UserDao userDao;
	
	@Autowired 
	LogRestfulDao logRestfulDao;
	
	@Autowired
	UserService userService;
	
	@Autowired
	private RealNameTmpDao tmpDao;
	
	@Value("${image.file.path.verifypic}")
	private String verifyPicPath; // 认证图片
	
	@Value("${image.file.path.userpic}")
    private String userPicPath;  //用户图片
	
	@Autowired
	private UserVerifyDao verifyDao;
	
	@Autowired UserDetailDao userdetailDao;
	
	@Value("${headimgurl.prefix}")
	private String headimgurlPrefix;
	
	@Autowired
	private SynDream2020Service synDream2020Service;
	
	@Autowired
	private SynScFireService synScFireService;
	
	@Autowired
	private SynLibraryService synLibraryService;
	
	@Autowired
	private SynCloudCollegeService synCloudCollegeService;
	
	/**
	 * 异步处理火堆保存用户信息业务
	 */
	@Async
	public void asyncSaveUserInfo(String logId,String unionid,String rleId,JSONObject realNameObject,JSONObject IdentityInfoObject,JSONObject bankInfoObject) {
		taskExecutor.execute(new Runnable() {
			@Override
			public void run() {
				processSaveUserInfo(logId,unionid,rleId,realNameObject,IdentityInfoObject,bankInfoObject);
			}
		});
	}
	
	private void processSaveUserInfo(String logId,String unionid,String rleId,JSONObject realNameObject,JSONObject IdentityInfoObject,JSONObject bankInfoObject) {
		String uid = realNameObject.getString("uid");

		UserEntity userEntity = userDao.queryUserByUid(uid);
		if (userEntity == null) {
			// 保存错误信息
			logRestfulDao.updateCheckResult("uid:"+uid+"没有对应用户", logId);
			return;
		}
		String phone = realNameObject.getString("phone");
		if(!StringUtils.isEmpty(phone)&&!StringUtils.isEmpty(phone.trim())
				&&!phone.trim().equals(userEntity.getPhone())) {
			if(userDao.countUserByPhoneAndNotUsedByUnionid(unionid,phone)==0) {
				 userDao.updatePhoneByUid(uid,phone);
			}else {
				logRestfulDao.updateCheckResult("uid:"+uid+"手机号："+phone+"已被使用", logId);
			}
		}
		
		
		String creFrontPicUrl = realNameObject.getString("creFrontPicUrl");
		String creReversePicUrl = realNameObject.getString("creReversePicUrl");
		
		if(StringUtils.isEmpty(creFrontPicUrl)||!creFrontPicUrl.contains(".")) {
			creFrontPicUrl = null;
		}
		if(StringUtils.isEmpty(creReversePicUrl)||!creReversePicUrl.contains(".")) {
			creReversePicUrl = null;
		}
		String creType = realNameObject.getString("creType");
		//负责人证件号  不做校验
		String creNum = realNameObject.getString("creNum");
		String realName = realNameObject.getString("realName");
		
		if(creFrontPicUrl != null) {
			String[]  creFrontPicArray = getFilePath(creFrontPicUrl.substring(creFrontPicUrl.lastIndexOf(".")),verifyPicPath);
			if(!Utils.downloadPicture(creFrontPicUrl, creFrontPicArray[0])) {
				//正面证件照加载失败 
				logRestfulDao.updateCheckResult("uid:"+uid+"证件照加载失败", logId);
				creFrontPicUrl = null;
			}else {
				creFrontPicUrl = creFrontPicArray[1];
			}
		}
		if(creReversePicUrl != null) {
			String[]  creReversePicArray = getFilePath(creReversePicUrl.substring(creReversePicUrl.lastIndexOf(".")),verifyPicPath);
			if(!Utils.downloadPicture(creReversePicUrl, creReversePicArray[0])) {
				//背面证件照加载失败  覆盖之前的结果 反正提示都一样 
				logRestfulDao.updateCheckResult("uid:"+uid+"证件照加载失败！", logId);
				creReversePicUrl = null;
			}else {
				creReversePicUrl = creReversePicArray[1];
			}
		}
		RealNameTmpEntity tmpEntity = tmpDao.queryTmpByUid(uid);
		if(tmpEntity == null) {
			tmpEntity = new RealNameTmpEntity();
			tmpEntity.setUid(uid);
			tmpEntity.setCts(new Date());
			tmpEntity.setCreator("huodui");
		}
		if(creFrontPicUrl != null) {
			tmpEntity.setCreFrontPic(creFrontPicUrl);
		}
		if(creReversePicUrl != null ) {
			tmpEntity.setCreReversePic(creReversePicUrl);
		}
	
		tmpEntity.setCreType(Integer.parseInt(creType));
		tmpEntity.setCreNum(creNum);
		tmpEntity.setRealName(realName);
		tmpEntity.setModifier("huodui");
		tmpEntity.setMts(new Date());
		tmpEntity.setDr(Constant.ONE);
		
		Integer sort = 0;
		switch (rleId) {
		case Constant.BUSINESS_ROLE_ID: //企业
			sort = 11;
			break;
		case Constant.ORG_ROLE_ID:  //社会组织
			sort = 13;
			break;
		case Constant.PUBLIC_WELFARE_TEAM_ROLE_ID:  //公益团队
			sort = 15;
			break;
		default:
			logRestfulDao.updateCheckResult("uid:"+uid+"角色非法", logId);
			return;
		}
		
		UserVerifyEntity verifyEntity = verifyDao.queryVerifyByUidAndRleId(uid, rleId);
		//其他角色先不管了
		
		if(verifyEntity == null) {
			verifyEntity = new UserVerifyEntity();
			verifyEntity.setUid(uid);
			verifyEntity.setRleId(rleId);
			verifyEntity.setSort(sort);
			verifyEntity.setCts(new Date());
			verifyEntity.setCreator("huodui");
		}
		//营业证 图片
		String idInfoCrePicUrl = IdentityInfoObject.getString("crePicUrl");
		if(StringUtils.isEmpty(idInfoCrePicUrl)||!idInfoCrePicUrl.contains(".")) {
			//不要设定值 用原先对象的
			//verifyEntity.setCrePic(null);
		}else {
			String[]  idInfoCrePicArray = getFilePath(idInfoCrePicUrl.substring(idInfoCrePicUrl.lastIndexOf(".")),verifyPicPath);
			if(!Utils.downloadPicture(idInfoCrePicUrl, idInfoCrePicArray[0])) {
				logRestfulDao.updateCheckResult("uid:"+uid+"营业证件照加载失败", logId);
				//verifyEntity.setCrePic(null);
			}else {
				verifyEntity.setCrePic(idInfoCrePicArray[1]);
			}
			
		}
		// (company,creNum,crePicUrl,intro,wechat,contact,phone)
		
		
		
		verifyEntity.setCompany(IdentityInfoObject.getString("company"));
		verifyEntity.setCreCode(IdentityInfoObject.getString("creCode"));
		verifyEntity.setIntro(IdentityInfoObject.getString("intro"));
		verifyEntity.setContact(IdentityInfoObject.getString("contact"));
		verifyEntity.setWechat(IdentityInfoObject.getString("wechat"));
		verifyEntity.setPhone(IdentityInfoObject.getString("phone"));
		verifyEntity.setState(1);	//重新保存 全部替换 审核中
		verifyEntity.setModifier("huodui");
		verifyEntity.setMts(new Date());
		verifyEntity.setDr(Constant.ONE);
		
		//(accountName,depositBank,aopenBranch,bankAccount)
		UserDetailEntity detailEntity = userdetailDao.queryUserDetailByUid(uid);
		if(detailEntity == null) {
			detailEntity = new UserDetailEntity();
			detailEntity.setUid(uid);
			detailEntity.setCts(new Date());
			detailEntity.setCreator("huodui");
		}
		detailEntity.setAccountName(bankInfoObject.getString("accountName"));
		detailEntity.setDepositBank(bankInfoObject.getString("depositBank"));
		detailEntity.setAopenBranch(bankInfoObject.getString("aopenBranch"));
		detailEntity.setBankAccount(bankInfoObject.getString("bankAccount"));
		detailEntity.setModifier("huodui");
		detailEntity.setMts(new Date());
		detailEntity.setDr(Constant.ONE);
		
		tmpDao.replaceRealNameTmp(tmpEntity);
		verifyDao.replaceVerifyByUidAndRleId(verifyEntity);
		userdetailDao.replaceIntoUserDetail(detailEntity);
	}
	
	//获取文件路径
	private String[] getFilePath(String ext,String filePath) {
		if(StringUtils.isEmpty(ext)) {
			ext = ".jpg";
		}
		switch (ext) {
		case ".jpg":
		case ".jpeg": ext = ".jpg";
		case ".png":
			break;
		default:
			ext = ".jpg";
			break;
		}
		String path = filePath.endsWith(File.separator) ? filePath : filePath + File.separator;
		File f = new File(path);
		if (!f.exists()) {
			f.mkdirs();
		}
		String fileName = Utils.parseDateToYearMonthDay(new Date()) + "-" + UUIDUtil.createUUID() + "." + ext;
		return new String[] {path+fileName,fileName};
	}
	
	@Async
	public void asyncUpdateUserBasicInfo(String uid, String avatarUrl, String nickname, String sex) {
		taskExecutor.execute(new Runnable() {
			public void run() {
				processUpdateUserBasicInfo(uid,avatarUrl,nickname,sex);
			}

			private void processUpdateUserBasicInfo(String uid, String avatarUrl, String uname, String sex) {
				if(StringUtils.isEmpty(uid)) {
					return;
				}
				UserEntity user = userDao.queryUserByUid(uid);
				//盒子
				SynDream2020DataModel data = new SynDream2020DataModel();
				//火堆
				SynScFireUserEntity scFireUser = new SynScFireUserEntity();
				//文库
				SynLibraryUserEntity libraryUser = new SynLibraryUserEntity();
				//真爱云学院
				SynCloudCollegeUserEntity cloudCollegeUser = new SynCloudCollegeUserEntity();
				
				
				if(user != null) {				
					if(!StringUtils.isEmpty(user.getUnionid())) {
						scFireUser.setUnionid(user.getUnionid());
					}
				}
				
				String oriUname = "";
				String oriSex = "";
				if(user != null) {
					oriUname = user.getUname();
					oriSex = user.getSex();
				}
				
				//开始处理基本信息
				if(sex != null) {
					switch (sex.trim()) {
					case "f":  
					case "F":  sex = Constant.FEMALE; break; 
					case "m": 
					case "M":  sex = Constant.MALE; break; 

					default:
						sex = null;
						break;
					}
				}
				int basicInfoRlt = userDao.updateSexAndUsernameByUid(uid,uname,sex);
				
				if(basicInfoRlt !=0) {
					if(!StringUtils.isEmpty(uname) && !uname.equals(oriUname)) {
						data.setCasid(uid);
						data.setName(uname);
						
						scFireUser.setUname(uname);
						
						libraryUser.setCasid(uid);
						libraryUser.setUname(oriUname);
						libraryUser.setUsername(uname);
						
						cloudCollegeUser.setCasId(uid);
						cloudCollegeUser.setNickName(uname);
					}
					if(!StringUtils.isEmpty(sex) && !sex.equals(oriSex)) {
						data.setCasid(uid);
						data.setSex(Constant.MALE.equals(sex) ? Constant.ONE : Constant.TWO);
						
						scFireUser.setGender(sex);
						
						cloudCollegeUser.setCasId(uid);
						cloudCollegeUser.setSex(sex);
					}
					
				}
				
				// 开始处理头像
				if (!StringUtils.isEmpty(avatarUrl) && avatarUrl.indexOf(headimgurlPrefix) == -1) {
					
					UserDetailEntity userDetail = userdetailDao.queryUserDetailByUid(uid);

					String ext = avatarUrl.substring(avatarUrl.lastIndexOf(".") + 1);
					if (StringUtils.isEmpty(ext) || "jpeg".equals(ext)) {
						ext = "jpg";
					}

					String imgPath = userPicPath.endsWith(File.separator) ? userPicPath : userPicPath + File.separator;
					String fileName = Utils.parseDateToYearMonthDay(new Date()) + "-" + UUIDUtil.createUUID() + "." + ext;
					boolean flag = Utils.downloadPicture(avatarUrl, imgPath + fileName);
					if (!flag) {
						return;
					}
					if (userDetail == null) {
						userDetail = new UserDetailEntity();
						userDetail.setUid(uid);
						userDetail.setCreator(uid);
						userDetail.setCts(new Date());
						userDetail.setModifier(uid);
						userDetail.setMts(new Date());
						userDetail.setDr(Constant.ONE);
						userdetailDao.addUserDetail(userDetail);
					} else {
						String oriPhoto = userDetail.getUser().getHeadimgurl();
						if (StringUtils.isEmpty(oriPhoto) || !oriPhoto.equals(fileName)) {
							String photo1 = userDetail.getPhoto1();
							String photo2 = userDetail.getPhoto2();
							userDetail.setPhoto1(oriPhoto);
							userDetail.setPhoto2(photo1);
							userDetail.setPhoto3(photo2);
							userDetail.setModifier(uid);
							userDetail.setMts(new Date());
							userdetailDao.updatePhoto(userDetail);
						}
					}

					if (user != null) {
						user.setHeadimgurl(fileName);
						user.setModifier(uid);
						user.setMts(new Date());
						userDao.updateHeadimg(user);
					}
					//头像同步数据
					String headimgurl =	headimgurlPrefix + uid;
					
					data.setCasid(uid);
					data.setAvatar(headimgurl);
					
					scFireUser.setImage(headimgurl);
					
					libraryUser.setCasid(uid);
					libraryUser.setAvatar(headimgurl);
					
					cloudCollegeUser.setCasId(uid);
					cloudCollegeUser.setHeadImgUrl(headimgurl);
				}
				
				
				//同步新版盒子数据
				if(!StringUtils.isEmpty(data.getCasid())) {
					synDream2020Service.synDream2020Data(data);
				}
				
				
				//同步火堆数据   
				//这个判断复杂点
				if(!StringUtils.isEmpty(scFireUser.getUname()) 
						|| !StringUtils.isEmpty(scFireUser.getGender()) 
						|| !StringUtils.isEmpty(scFireUser.getImage()) ) {
					synScFireService.synScFireUser(scFireUser);
				}
						
				//同步梦想文库数据
				if(!StringUtils.isEmpty(libraryUser.getCasid())) {
					synLibraryService.synLibraryUser(libraryUser);
				}
				//同步真爱云学院	
				if(!StringUtils.isEmpty(cloudCollegeUser.getCasId())) {	
					synCloudCollegeService.synLibraryUser(cloudCollegeUser);
				}
			}
			
		});
	}
}
